package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import ch.qos.logback.core.net.server.Client;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.nursing.domain.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductByProductKeyVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.nursing.vo.PropertiesVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备表Service业务层处理
 *
 * @author Adam
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient ioTDAClient;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备表
     *
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateDevice(Device device) {
        //删除该位置数据
        boolean rm = this.removeById(device);
        if (rm == false) {
            throw new BaseException("删除失败");
        }
        //判断该位置是否有相同的设备
        Integer locationType = device.getLocationType();
        Integer physicalLocationType = device.getPhysicalLocationType();
        String productKey = device.getProductKey();
        String bindingLocation = device.getBindingLocation();
        long count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getLocationType, locationType)
                .eq(physicalLocationType != null, Device::getPhysicalLocationType, physicalLocationType)
                .eq(Device::getProductKey, productKey)
                .eq(Device::getBindingLocation, bindingLocation)
        );
        if (count > 0) {
            throw new BaseException("该位置已有相同类型设备");
        }
        //添加设备
        boolean flag = this.save(device);
        //更新IOT平台中设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(device.getDeviceName());
        request.setBody(body);
        UpdateDeviceResponse updateDeviceResponse = ioTDAClient.updateDevice(request);
        if (updateDeviceResponse.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new BaseException("IOT平台更新失败");
        }
        return flag ? 1 : 0;
    }

    /**
     * 批量删除设备表
     *
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     *
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步设备数据
     */
    @Override
    public void SyncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = ioTDAClient.listProducts(request);
        if (response.getHttpStatusCode() != HttpStatus.SUCCESS) {
            throw new BaseException("设备列表查询错误");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> AllProduct() {
        Object object = redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if (ObjectUtil.isEmpty(object)) {
            return Collections.emptyList();
        }
        List<ProductVo> list = JSONUtil.toList(object.toString(), ProductVo.class);
        return list;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(DeviceDto dto) {
//        判断设备名称是否重复
        if (count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName())) > 0) {
            throw new BaseException("设备名称重复");
        }
//        设备标识是否重复
        if (count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId())) > 0) {
            throw new BaseException("设备标识重复");
        }
//        同一位置是否绑定了相同的产品
        if (count(Wrappers
                .<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getLocationType())
        ) > 0) {
            throw new BaseException("老人已绑定该产品,请重新选择");
        }

//        注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());

        //设置密钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response = ioTDAClient.addDevice(request);
//        本地保存
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        device.setIotId(response.getDeviceId());
        save(device);
    }

    /**
     * 查询设备详细数据
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDevice(String iotId) {
        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        //根据产品和设备查询详情信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        ShowDeviceResponse response = ioTDAClient.showDevice(request.withDeviceId(iotId));
        deviceDetailVo.setDeviceDescription(response.getDescription());
        String activeTime = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTime)) {

            // 日期格式转换 - 使用正确的ISO日期时间格式
            LocalDateTime dateTime = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            // 日期时区转换
            deviceDetailVo.setActiveTime(DateTimeZoneConverter.utcToShanghai(dateTime));


        }
        deviceDetailVo.setDeviceStatus(response.getStatus());
        //根据设备id查看设备
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        //合并数据
        BeanUtil.copyProperties(device, deviceDetailVo);
        return deviceDetailVo;
    }

    /**
     * 查看设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        //获取操作时间
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
        if (response.getShadow().size() == 0 || response.getShadow() == null) {
            return null;
        }
        List<DeviceShadowData> shadow = response.getShadow();

        DeviceShadowData shadowData = shadow.get(0);
        String eventTime = shadowData.getReported().getEventTime();
        LocalDateTime dateTime = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");

        //时区转换
        LocalDateTime eventTimeStr = DateTimeZoneConverter.utcToShanghai(dateTime);
        System.out.println(eventTimeStr);

        JSONObject jsonObject = JSONUtil.parseObj(shadowData.getReported().getProperties());


        jsonObject.forEach((key, value) -> {
            HashMap<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTimeStr);
            mapList.add(map);
        });

        return mapList;
    }

    /**
     * 删除设备
     *
     * @param iotId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDevice(String iotId) {
        //删除数据库数据
        this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        //删除IOT平台设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        ioTDAClient.deleteDevice(request);

    }

    /**
     * 查询产品详情(报警规则模块使用)
     *
     * @param productKey
     * @return
     */
    @Override
    public ProductByProductKeyVo queryProductByProductKey(String productKey) {
        //设置返回值
        ProductByProductKeyVo productByProductKeyVo = new ProductByProductKeyVo();
        List<PropertiesVo> propertiesVos = new ArrayList<>();

        //获取产品信息
        ShowProductRequest request = new ShowProductRequest();
        ShowProductRequest showProductRequest = request.withProductId(productKey);
        ShowProductResponse response = ioTDAClient.showProduct(showProductRequest);



        productByProductKeyVo.setService_id(response.getAppId());
        productByProductKeyVo.setService_type(response.getDeviceType());
        response.getServiceCapabilities().forEach(serviceCapability -> {
            PropertiesVo propertiesVo = new PropertiesVo();
            propertiesVo.setData_type(serviceCapability.getServiceType());
            propertiesVo.setDescription(serviceCapability.getDescription());
            propertiesVo.setDescription(serviceCapability.getDescription());
            propertiesVos.add(propertiesVo);
        });

        productByProductKeyVo.setProperties(propertiesVos);
        return productByProductKeyVo;
    }
}
